<template>
  <div class="upload-container">
    <el-upload
      v-loading="loading"
      action="#"
      class="uploadImage"
      :class="{disabled:uploadDisabled}"
      list-type="picture-card"
      :on-change="handleChange"
      accept="png,jpg,jpeg,PNG"
      :auto-upload="false"
      :file-list="imagelist"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <div id="tip" style="font-size:12px;color:rgb(125 119 119)" />
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true" :modal-append-to-body="false">
      <img width="100%" :src="imageUrlDiaLog" alt="">
    </el-dialog>
  </div>
</template>

<script>
import * as imageConversion from 'image-conversion'
import { uploadImg, uploadDownload } from '@/api/uploadImg'

export default {
  name: 'Upload',
  props: {
    imageUrl: {
      // type: String,
      // default: ''
    },
    tip: {
      type: String,
      default: '提示：只能上传jpg/png文件，且不超过5M'
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      imagelist: [],
      tips: '',
      imageUrlDiaLog: ''
    }
  },
  computed: {
    uploadDisabled() {
      return this.imagelist.length > 0
    }
  },
  watch: {
    tips(value) {
      document.getElementById('tip').innerHTML = value
    },
    'imageUrl': {
      immediate: true,
      handler: function async(value) {
        if (value != null && value.length > 0) {
          if(value.toString()[0] == '['){
            value = JSON.parse(value);
            for(const item of value){
              uploadDownload({
                fileId: item
              }).then(res => {
                this.imagelist.push({name:'',fileId:item,url:'data:image/png;base64,' + res.data})
              })
            }
          }else{
            uploadDownload({
              fileId: value
            }).then(res => {
              this.imagelist = value ? [{
                fileId:value,
                name: '',
                url: 'data:image/png;base64,' + res.data
              }] : []
            })
          }
        } else {
          this.imagelist = []
        }
      }
    }
  },

  created() {
    this.tips = this.tip
  },

  beforeUpdate() {
    this.tips = this.tip
  },

  methods: {
    handleRemove(file,fileList) {
      this.$emit('delImg',file.fileId)
      if(fileList.length === 0){
        this.imagelist = []
        this.$emit('imageUrl', '')
      }
    },
    handlePictureCardPreview(file) {
      this.imageUrlDiaLog = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      this.imagelist = fileList
      const isLt1M = file.size / 1024 / 1024 < 1
      const MJsize = file.size / 1024 / 1024;
      const formDate = new FormData()
      this.loading = true
      if (!isLt1M) {
        imageConversion.compressAccurately(file.raw, MJsize<2?1000:MJsize > 20?100:10 < MJsize < 20?200:5< MJsize <10?300:500).then(res => {
          res.name = file.raw.name;
          const files = new window.File([res],res.name,{type:res.type})
          formDate.append('file', files)
          uploadImg(formDate).then(res => {
            this.loading = false
            this.$emit('imageUrl', res.data.fileId)
          })
        })
      } else {
        formDate.append('file', file.raw)
        uploadImg(formDate).then(res => {
          this.loading = false
          this.$emit('imageUrl', res.data.fileId)
        })
      }
    }
  }
}
</script>
